package cn.fl.ref.fncprjnormalsettle.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjeaplysettle.service.IFncPrjEaplySettleService;
import cn.fl.ref.fncprjeaplysettle.transform.SettlePrjDetailVOTransform;
import cn.fl.ref.fncprjeaplysettle.vo.SettlePrjDetailVO;
import cn.fl.ref.fncprjfstpyinfo.service.IFncPrjFstpyInfoService;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.scmbaseinfo.service.IScmBaseInfoService;
import cn.fl.ref.scmbaseinfo.vo.ScmBaseInfoVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.fncprjeaplysettle.condition.FncPrjEaplySettleQueryCondition;
import fl.ref.fncprjeaplysettle.constant.FncPrjEaplySettleConstant;
import fl.ref.fncprjeaplysettle.dto.SettlePrjDetailDTO;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.scmbaseinfo.condition.ScmBaseInfoQueryCondition;

/**
 * @Description: 正常结清
 */
@Controller
@RequestMapping("/rfbase/fncprjnormalsettle")
public class FncPrjNormalSettleController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncPrjNormalSettleController.class);

	@Autowired
	private IFncPrjEaplySettleService fncPrjEaplySettleService;
	
	@Autowired
	private IFriBaseInfoService friBaseInfoService;

	@Autowired
	private IScmBaseInfoService scmBaseInfoService;
	
	@Autowired
	private IFncPrjFstpyInfoService fncPrjFstpyInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET })
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("加载正常结清列表页面.");
		ModelAndView view = new ModelAndView("/rfbase/fncprjnormalsettle/fncPrjNormalSettleList");
		// 融资机构
		List<FriBaseInfoVO> friBaseInfoVOs = friBaseInfoService.searchList(new FriBaseInfoQueryCondition());
		List<KeyValueVO> fundRasInsNmList = fncPrjFstpyInfoService.transformToKeyValue(friBaseInfoVOs, FriBaseInfoVO.class.getName(), "id",
				"fundRasInsNm");
		view.addObject("fundRasInsNmList", fundRasInsNmList);
		// 融资方案
		List<ScmBaseInfoVO> scmBaseInfoVOs = scmBaseInfoService.selectBscLstByCondition(new ScmBaseInfoQueryCondition());
		List<KeyValueVO> fncScmNmList = fncPrjFstpyInfoService.transformToKeyValue(scmBaseInfoVOs, ScmBaseInfoVO.class.getName(), "fncScmId",
				"fncScmNm");
		view.addObject("fncScmNmList", fncScmNmList);
		view.addObject("frilist", JSON.toJSONString(friBaseInfoVOs));
		return view;
	}

	/**
	 * 初始化列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String fncInsId = request.getParameter("fncInsId");
		String fncScmId = request.getParameter("fncScmId");
		String fncPrjNm = request.getParameter("fncPrjNm");
		String fncSettleStcd = request.getParameter("fncSettleStcd");

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		FncPrjEaplySettleQueryCondition qc = new FncPrjEaplySettleQueryCondition();
		
		if (StringUtils.isNotEmpty(fncInsId)) {
			qc.setFncInsId(fncInsId);
		}
		if (StringUtils.isNotEmpty(fncScmId)) {
			qc.setFncScmId(fncScmId);
		}
		if (StringUtils.isNotEmpty(fncPrjNm)) {
			qc.setFncPrjNm(fncPrjNm);
		}
		if (StringUtils.isNotEmpty(fncSettleStcd)) {
			qc.setFncSettleStcd(fncSettleStcd);
		}else {
			qc.setFncSettleStcd("7,10"); // 正常和正常结清中
		}
		qc.setSettleType(FncPrjEaplySettleConstant.SETTLE_TYPE_NORMAL); // 正常结清类型列表
		page.setCondition(qc);

		Pager pager = this.fncPrjEaplySettleService.selectSettlePrjDetailListPage(page);
		List<SettlePrjDetailDTO> listDtos = (List<SettlePrjDetailDTO>) pager.getResultList();
		List<SettlePrjDetailVO> list = SettlePrjDetailVOTransform.toVOList(listDtos);
		ListPageVO<SettlePrjDetailVO> listPage = new ListPageVO<SettlePrjDetailVO>(list, pager.getTotalCount());

		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 审核流程
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) {

		String fncPrjId = request.getParameter("fncPrjId");
		String procDefKey = request.getParameter("procDefKey");
		String procDefId = request.getParameter("procDefId");
		String procNo = request.getParameter("procNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if (StringUtils.isEmpty(fncPrjId)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			// 流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(FncPrjEaplySettleConstant.REF_FLOW_S_H_FPNS);
			flowStartParamsDTO.setProcDefKey(procDefKey);
			flowStartParamsDTO.setProcDefId(procDefId);
			flowStartParamsDTO.setProcNo(procNo);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setBusinessKey(fncPrjId);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);// 优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(FncPrjEaplySettleConstant.FLOW_BUSINESS_TYP_FNC_PRJ_BSC_INFO);// 确认用不用
			flowStartParamsDTO.setModelTyp(FncPrjEaplySettleConstant.FLOW_MODEL_TYP_FPNS);// 需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm() + "、首付款流程大字段参数未定!");
			DataResultDTO dataResultDTO = this.fncPrjEaplySettleService.addNormalSettleFlowStart(flowStartParamsDTO);
			if (!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if (null != dataResultDTO && null != dataResultDTO.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if (StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:" + flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功");
				}
			}
			/*
			 * if(null != dataResultDTO.getInfo() && StringUtils.isNotEmpty(dataResultDTO.getInfo())){ StringBuffer info = new StringBuffer();
			 * info.append(result.getInfo()); info.append(SysLogConstant.LOG_FLOW_NEXT_TASK_OPERATOR); info.append(dataResultDTO.getInfo());//操作人
			 * result.setInfo(info.toString()); }
			 */
		} catch (BaseException e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e.getMessage());
			BaseLogUtils.info(logger, "addFlowStart",
					"错误[BaseException],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(),
					CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addFlowStart",
					"错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(),
					CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		}
		return result;
	}

}
